<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
    >
      <el-form-item label="设备编号" prop="deviceCode">
        <el-input
          v-model="queryParams.deviceCode"
          placeholder="请输入设备编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设备名称" prop="deviceName">
        <el-input
          v-model="queryParams.deviceName"
          placeholder="请输入设备名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="申请人" prop="operUserId">
        <UserDialog v-model="queryParams.operUserId"></UserDialog>
      </el-form-item>
      <el-form-item label="检验部门" prop="deptId">
        <el-cascader
         :props="{ value: 'id', checkStrictly: true }"
              :show-all-levels="false"
          placeholder="请选择部门"
          v-model="queryParams.deptId"
          :options="deptOptions"
        ></el-cascader>
      </el-form-item>
      <el-form-item label="日期">
        <el-date-picker
          v-model="dateRange"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          style="width: 240px"
          :default-time="['00:00:00', '23:59:59']"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:user:add']"
          >新增</el-button
        >
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['equipment:register:register']"
          >登记</el-button
        >
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:user:remove']"
          >删除</el-button
        >
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['equipment:register:export']"
          >导出</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="printBox"
          v-hasPermi="['equipment:deviceEmpower:print']"
          >打印</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      @selection-change="handleSelectionChange"
      fit
      v-loading="loading"
      border
      :data="dataList"
    >
      <el-table-column type="selection" width="55" align="center" />

      <el-table-column
        width="80"
        label="设备编号"
        :show-overflow-tooltip="true"
      >
        <template slot-scope="scope">
          <el-link

            v-if="scope.row.deviceCode"
            @click="handleDetail(scope.row)"
            type="primary"
            >{{ scope.row.deviceCode }}</el-link
          >
          <span v-else>--</span>
        </template>
      </el-table-column>
      <el-table-column width="150" label="设备名称" prop="deviceName" />

      <el-table-column show-overflow-tooltip label="设备状态" width="100">
        <template slot-scope="scope">
          <el-tag size="mini" :type="scope.row.status == 4?'danger': scope.row.status == 3?'warning':scope.row.status == 0?'info':'success'">{{scope.row.statusName }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        :show-overflow-tooltip="true"
        width="120"
        label="生产厂家"
        prop="manufacturer"
      />
      <el-table-column
        :show-overflow-tooltip="true"
        width="120"
        label="规格型号"
        prop="spec"
      />
      
      <el-table-column show-overflow-tooltip prop="checkScope" label="测量范围" width="120">
      </el-table-column>
      <el-table-column
        :show-overflow-tooltip="true"
        width="120"
        label="所属部门 "
        prop="deptName"
      />
      <el-table-column show-overflow-tooltip prop="site" label="位置" >
     
      </el-table-column>
    
      <el-table-column
        :show-overflow-tooltip="true"
        width="120"
        label="管理人"
        prop="managerUserName"
      />
      <el-table-column show-overflow-tooltip width="100" label="检定方式" prop="checkPeriod">
        <template slot-scope="scope">{{ scope.row.checkType == 1 ? "准用" :scope.row.checkType == 0? "检定":'' }}</template>
      </el-table-column>
     
      <el-table-column show-overflow-tooltip width="130" label="上次检定/校准日期" prop="checkDate" />
      <el-table-column show-overflow-tooltip width="130" label="校准/计量检定周期" prop="checkPeriod">
        <template slot-scope="scope">{{ scope.row.checkPeriod }}个月</template>
      </el-table-column>
      <el-table-column show-overflow-tooltip width="130" label="下次检定/校准日期" prop="effectDate" />

      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="200"
        fixed="right"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            v-hasPermi="['equipment:all:info:card']"
            @click="handleDetail(scope.row)"
            >设备信息卡</el-button
          >
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            v-hasPermi="['equipment:register:info']"
            @click="handleDetail(scope.row)"
            >详情</el-button
          >
          <el-button
            v-if="scope.row.isComplete != 1"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['equipment:register:register']"
            >登记</el-button
          >
          <el-button
            v-if="scope.row.managerAudit ==2"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate2(scope.row)"
            v-hasPermi="['equipment:register:register']"
            >修改</el-button
          >
          <el-button
          v-if="scope.row.isComplete == 1"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate2(scope.row,true)"
            v-hasPermi="['equipment:register:edit:manger']"
            >管理员修改</el-button
          > -->

           <!-- <el-button
            v-show="(scope.row.managerAudit == 0)&&scope.row.isComplete == 1"
            size="mini"
            type="text"
            @click="handleAudit(scope.row)"
            v-hasPermi="['equipment:register:aduit']"
            >审核</el-button
          >

          <el-button
            size="mini"
            type="text"
            v-hasPermi="['company:certificate:info']"
            @click="handleCode(scope.row)"
            >小程序查看</el-button
          >
          <el-button
          v-if="scope.row.isComplete == 1"
            size="mini"
            type="text"
            v-hasPermi="['equipment:register:history:record']"
            @click="handleRecord(scope.row)"
            >设备流转记录</el-button
          > -->

          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['company:news:remove']"
            >删除</el-button
          > -->
        </template>
      </el-table-column>
      </el-table>
       <el-dialog
      title="审核"
      :visible.sync="openAudit"
      width="700px"
      append-to-body
    >
      <el-form
        ref="elForm"
        :model="formData"
        :rules="rules"
        size="medium"
        label-width="100px"
      >
        <el-form-item label="审核结果" prop="managerAudit">
          <el-radio-group v-model="formData.managerAudit">
            <el-radio label="1">审核通过</el-radio>
            <el-radio label="2">审核不通过</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="审核原因"
          v-if="formData.managerAudit == 2"
          prop="managerCause"
        >
          <el-input
            v-model="formData.managerCause"
            placeholder="请输入审核原因"
            clearable
            :style="{ width: '100%' }"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="openAudit = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 打印模板位置 -->
    <PrintBox
      :pageNum="queryParams.pageNum"
      :total="total"
      :printRow="printList"
      :isVertical="false"
      :isPageSize="false"
      id="printBox"
    >
      <template slot="title" slot-scope="scope">
        <div style="margin-bottom: 40px">设备情况登记表 STET/B/20-1</div>
      </template>
      <template slot-scope="scope">
        <!-- 表格  class  table-page  必须-->
        <table
          style="border-collapse: collapse; table-layout: fixed; width: 100%"
          border="1"
          cellspacing="0"
          class="table-page"
          :isVertical="false"
        >
          <tr style="height: 16mm">
            <td>设备名称</td>
            <td colspan="2">{{ scope.item.deviceName }}</td>
            <td>设备编号</td>
            <td>{{ scope.item.deviceCode }}</td>
            <td colspan="2" rowspan="4">
              <img
                style="width: 280px; height: 250px;object-fit: cover"
                :src="$VUE_APP_IMG_API+scope.item.image"
              ></img>
            </td>
          </tr>
          <tr style="height: 16mm">
            <td>规格编号</td>
            <td colspan="2">{{ scope.item.spec }}</td>
            <td>出厂编号</td>
            <td>{{ scope.item.code }}</td>
          </tr>
          <tr style="height: 16mm">
            <td>制造厂商</td>
            <td colspan="2">
              {{ scope.item.manufacturer }}
              <!-- {{
                checkDict(
                  dict.type.sys_manufacturer_list,
                  scope.item.manufacturer
                )
              }} -->
            </td>
            <td>出厂日期</td>
            <td>{{ scope.item.factoryDate }}</td>
          </tr>
          <tr style="height: 16mm">
            <td>供应商</td>
            <td colspan="2">{{ scope.item.supplierName }}</td>
            <td>联系方式</td>
            <td>{{ scope.item.phone }}</td>
          </tr>
          <tr style="height: 16mm">
            <td>移交附件</td>
            <td colspan="3">{{ scope.item.turnAttachment||''}}</td>
            <td>允许操作人员</td>
            <td colspan="2">
              {{ scope.item.operUserName }}
            </td>
          </tr>
          <tr style="height: 16mm">
            <td>设备用途</td>
            <td colspan="3">{{ scope.item.useInfo }}</td>
            <td>管理人</td>
            <td colspan="2">{{ scope.item.managerUserName }}</td>
          </tr>
          <tr style="height: 16mm">
            <td>操作规程</td>
            <td colspan="2">
              <div style="text-align: center;display: flex;align-items: center;">
                <input
                  type="checkbox"
                  :checked="scope.item.operStandard == 0"
                />有，受控编号{{ scope.item.standardCode }}
              </div>
              <div style="text-align: center;display: flex; align-items: center;">
                <input
                  type="checkbox"
                  :checked="scope.item.operStandard == 1"
                />无
              </div>
            </td>
            <td>操作视频</td>
            <td>
              <div style="text-align: center;display: flex;
    align-items: center;justify-content: center;">
                <input :checked="scope.item.isVideo == 0" type="checkbox" />有
              </div>
              <div style="text-align: center;display: flex;
    align-items: center;justify-content: center;">
                <input :checked="scope.item.isVideo == 1" type="checkbox" />无
              </div>
            </td>
            <td style="width: 10px">校验/计量检定周期</td>
            <td>{{ scope.item.checkPeriod }}月</td>
          </tr>
          <tr style="height: 16mm">
            <td>维护保养内容</td>
            <td colspan="2">{{ scope.item.careContent }}</td>
            <td>维护保养周期</td>
            <td>{{ scope.item.carePeriod }}月</td>
            <td>溯源方式</td>
            <td>
              {{
                checkDict(dict.type.sys_trace_method, scope.item.traceMethod)
              }}
            </td>
          </tr>
          <tr style="height: 16mm">
            <td>测量范围</td>
            <td colspan="2">{{ scope.item.checkScope }}</td>
            <td>扩展不确定度/最大允差/准确度等级</td>
            <td>{{ scope.item.checkLevel }}</td>
            <td>分度值</td>
            <td>{{ scope.item.scaleValue }}</td>
          </tr>
          <tr style="height: 16mm">
            <td>精度</td>
            <td colspan="2">{{ scope.item.scale }}</td>
            <td>所属部门</td>
            <td>{{ scope.item.deptName }}</td>
            <td>位置</td>
            <td>{{ scope.item.site }}</td>
          </tr>
        </table>
        <!-- 底部信息位置 -->
        <div class="page-bottom" style="page-break-after: always">
          <div class="desc">注：本表格自2021年6月1日起生效</div>
        </div></template
      ></PrintBox
    >
    <el-dialog
      :visible.sync="showCode"
      title="小程序查看"
      width="300px"
      append-to-body
    >
      <div style="text-align: center">
        <vue-qr :text="textUrl" :size="200"></vue-qr>
      </div>
    </el-dialog>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <el-dialog
      :title="titleLog"
      :visible.sync="openLog"
      width="700px"
      append-to-body
    >
      <el-table
        v-if="openLog"
        fit
        v-loading="loadingLog"
        :data="dataPayLogList"
      >
      <el-table-column
            :render-header="lableRender"
          >
          <el-table-column
            label="所在部门"
            min-width="150"
            prop="deptName"
            :show-overflow-tooltip="true"
          >
          </el-table-column>
          <el-table-column label="所在位置" min-width="150" show-overflow-tooltip >
            <template slot-scope="scope">
              <dict-tag
            :options="dict.type.sys_site_list"
            :value="scope.row.site"
             />
            </template>
          </el-table-column>
          <el-table-column label="所在日期" min-width="200" show-overflow-tooltip >
            <template slot-scope="scope">
              {{ scope.row.startTime }}~{{ scope.row.endTime?scope.row.endTime:'至今' }}
            </template>
          </el-table-column>
          </el-table-column>

      </el-table>
      <pagination
      v-show="dataPayLogList.length"
      :total="totalLog"
      :page.sync="logParams.pageNum"
      :limit.sync="logParams.pageSize"
      @pagination="getListLog"
    />
    </el-dialog>
  </div>
</template>

<script>
import { allList, delDevice,deviceAudit } from "@/api/device/device.js";
import { deptTreeSelect } from "@/api/system/user.js";
import printStyle from "@/utils/print.js";
import {
  listwanderHistory,
} from "@/api/device/wanderHistory.js";
export default {
  name: "Register",
  dicts: ["sys_manufacturer_list", "sys_site_list", "sys_trace_method"],

  data() {
    return {
      openAudit: false,
      formData: {
        managerAudit: "1",
      },
      rules: {
        managerCause: [
          {
            required: true,
            message: "拒绝原因不能为空",
            trigger: "blur",
          },
        ],
      },
      showCode: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      dataList: [],
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      deptOptions: [],
      // 查询参数
      queryParams: {
        // isComplete:1,
        deptId: [],
        deviceCode: undefined,
        pageNum: 1,
        pageSize: 10,
        title: undefined,
        operUserId: undefined,
        licenseNum: undefined,
        checkDate: null,
      },
      // 日期范围
      dateRange: [],

      userList: [],
      deptOptions: [],
      currentInfo: {},
      textUrl: "",
      infos: [], //勾选的数据
      printList: [],
      dataPayLogList: [],
      logParams: {
        pageNum: 1,
        pageSize: 10,
        id: undefined,
        from:1
      },
      titleLog: "流转记录",
      openLog: false,
      loadingLog: false,
      totalLog:0
    };
  },
  created() {
    const str = sessionStorage.getItem('queryParams');
    console.log();
    if (str) {
      this.queryParams = JSON.parse(str)
      if (this.queryParams.startEndDate) {
        this.dateRange.push(this.queryParams.startEndDate, this.queryParams.endEndDate)
      }
      setTimeout(() => {
        sessionStorage.removeItem('queryParams');
      }, 500)
    }
    this.getList();
    this.getDeptTree();
  },
  methods: {
    lableRender(e) {
        return (
          <el-row  style={{textAlign:'center'}}  type="flex" justify="space-around">
            <el-col span='8'>设备编号：{this.dataPayLogList[0]&&this.dataPayLogList[0].deviceCode}</el-col>
            <el-col span='8'>设备名称：{this.dataPayLogList[0]&&this.dataPayLogList[0].deviceName}</el-col>
            <el-col span='8'>设备型号：{this.dataPayLogList[0]&&this.dataPayLogList[0].spec}</el-col>
          </el-row>
        );
    },
    /* 设备流转记录 */
    handleRecord(e){
      this.logParams.deviceId = e.deviceId
      this.openLog = true
      this.getListLog()
    },
    getListLog(){
      this.loadingLog = true;
      listwanderHistory(this.logParams).then((response) => {
        this.dataPayLogList = response.rows;
        this.loadingLog = false;
      });
    },
    printBox() {
      //infos  勾选的数据 如果有勾选就打印勾选。
      if (this.infos.length) {
        this.printList = this.infos;
      } else {
        //反之打印当前整个列表
        this.printList = this.dataList;
      }
      setTimeout(() => {
        document.title = "设备情况登记表 STET/B/20-1";

        this.$print({
          printable: "printBox", //打印区域id
          type: "html", //打印类型是html
          scanStyles: false,
          targetStyles: ["*"],
          style: this.workStyle(),
          onPrintDialogClose: () => {
            document.title = process.env.VUE_APP_TITLE;
          },
        });
      }, 500);
    },
    // 可以自定义样式  printStyle 是公共样式 切勿私自修改
    workStyle() {
      return `${printStyle}
        table,
        table tr th,
        table tr td {
          padding: 4px;
        }
        .desc{
        text-align: left; font-size: 12px; margin-top: 10px
      }
            .df {
                display: flex;
              }
      `;
    },
    handleCode(e) {
      this.textUrl =
        process.env.VUE_APP_CODE_API + "deviceDetail?id=" + e.deviceId;
      this.showCode = true;
    },
    handleBus(row) {
      console.log(row.isStartPiid);
      if (row.isStartPiid !== 2) return;
      const pathList = [
        {
          path: "/register/process/detail/",
          id: "deviceId",
          name: "设备情况登记",
        },
        {
          path: "/deviceConfirm/process/detail/",
          id: "deviceConfirmId",
          name: "设备(工具)符合性确认",
        },
        {
          path: "/deviceStatus/process/detail/",
          id: "deviceStatusId",
          name: "维修",
        },
        {
          path: "/deviceStatus/process/detail/",
          id: "deviceStatusId",
          name: "停用",
        },
        {
          path: "/deviceStatus/process/detail/",
          id: "deviceStatusId",
          name: "报废",
        },
        {
          path: "/deviceStatus/process/detail/",
          id: "deviceStatusId",
          name: "恢复",
        },
        {
          path: "/checkAsk/process/detail/",
          id: "deviceCheckAskId",
          name: "仪器设备计量检定要求",
        },
        {
          path: "/checkAsk/process/detail/",
          id: "deviceCheckAskId",
          name: "上传外部检测证书(维修) ",
        },
        {
          path: "/checkAsk/process/detail/",
          id: "deviceCheckAskId",
          name: "上传外部检测证书(检定) ",
        },
        {
          path: "/resultConfirm/process/detail/",
          id: "deviceResultConfirmId",
          name: "设备校准结果符合性确认 ",
        },

        // 待办业务 - -1-无 0-设备情况登记 1-设备(工具)符合性确认 2-维修 3-停用 4-报废 5-恢复
        // 6-仪器设备计量检定要求 7-上传外部检测证书(维修) 8-上传外部检测证书(检定) 9-设备校准结果符合性确认
      ];
      let pathInfo = pathList[row.busStatus];
      this.$router.push({
        path: pathInfo.path + row.piid,
        query: {
          definitionId: null,
          deployId: null,
          taskId: null,
          finished: false,
          id: row.busId,
        },
      });
    },
    handleExport() {
      this.download(
        "system/device/allExport",
        {
          ...this.queryParams,
          ids:this.ids.toString(),
          deptId: this.queryParams.deptId.slice(-1)[0],
        },
        `设备总表_${this.parseTime(
          new Date().getTime(),
          "{y}-{m}-{d}"
        )}.xlsx`
      );
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.deviceId);
      this.infos = selection;
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      const configId = row.deviceId || this.ids;
      let e = this.dataList.find((i) => i.deviceId == configId);
      if (e.isComplete == 1) {
        this.$message.warning("信息补充完整，不允许修改");
        return;
      }
      this.$router.push("./addRegister?isEdit=true&id=" + configId);
    },
    handleUpdate2(row,isAdminOpt) {
      const configId = row.deviceId || this.ids;
      this.$router.push("./addRegister?isEdit=true&id=" + configId+'&isAdminOpt='+isAdminOpt);
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then((response) => {
        this.deptOptions = response.data;
      });
    },
    checkName(e) {
      console.log(e, "name");
    },
    handleDetail(row) {
      // sessionStorage.setItem('pageNum', this.queryParams.pageNum);
      sessionStorage.setItem('queryParams', JSON.stringify(this.queryParams));

      this.$router.push("./equipmentInfoCard?isInfo=true&id=" + row.deviceId);
      // this.$router.push({
      //   path: "/register/process/detail/" + row.piid,
      //   query: {
      //     definitionId: null,
      //     deployId: null,
      //     taskId: null,
      //     finished: false,
      //     id: row.deviceId,
      //   },
      // });
    },
    handleAudit(row) {
      this.formData = {
        managerAudit: "1",
        deviceId: row.deviceId,
      };
      this.openAudit = true;
    },
    submitForm: function () {
      this.$refs["elForm"].validate((valid) => {
        if (valid) {
          let query = JSON.parse(JSON.stringify(this.formData));
          deviceAudit(query).then((response) => {
            this.$modal.msgSuccess("审核成功");
            this.openAudit = false;
            this.getList();
          });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const configId = row.deviceId || this.ids;

      this.$modal
        .confirm('是否确认删除ID为"' + configId + '"的数据项？')
        .then(function () {
          return delDevice(configId);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    handleAdd() {
      this.$router.push("./addRegister");
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      allList({
        ...this.addDateRangeTime(
          this.queryParams,
          this.dateRange,
          "startEndDate",
          "endEndDate"
        ),
        deptId: this.queryParams.deptId.slice(-1)[0],
      }).then((response) => {
        this.dataList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep .el-dialog__body {
  img {
    width: 100%;
  }
}
</style>
